//app.js

App({
	onLaunch: function () {
		let that = this;
		//调用API从本地缓存中获取数据
		var logs = wx.getStorageSync('logs') || []
		logs.unshift(Date.now())
		wx.setStorageSync('logs', logs);
		//授权后开始登陆
		wx.getSetting({
			success(res) {
				if (res.authSetting['scope.userInfo']) {

					that.getUserInfo();
				}
			}
		})
	},
	getUserInfo: function (cb) {
		var that = this;
		wx.getStorage({
			key: 'userInfo',
			success: function (res) {

			},

		})
		wx.login({
			success: function (res) {
				var code = res['code'];
				//2.小程序调用wx.getUserInfo得到rawData, signatrue, encryptData.
				wx.getUserInfo({
					success: function (info) {
						var rawData = info['rawData'];
						var signature = info['signature'];
						var encryptData = info['encryptData'];
						var encryptedData = info['encryptedData'];
						var iv = info['iv'];
						wx.request({
							url: that.globalData.url + 'login',
							data: {
								"code": code,
								"rawData": rawData,
								"signature": signature,
								"encryptData": encryptData,
								'iv': iv,
								'encryptedData': encryptedData
							},
							success: function (res) {
								//将用户数据存于缓存中
								wx.setStorage({
									key: 'userInfo',
									data: res.data,
								})
								console.log("更新缓存");
								that.globalData.userInfo = res;
								typeof cb == "function" && cb(that.globalData.userInfo)
								wx.hideLoading()
							}
						});
					}
				});

			}
		});
	},
	//其他页面调用登陆功能
	login: function (cb) {
		let that = this;
		that.getUserInfo();
		//首选询问是否登陆，如果没有登陆的话就跳转到个人中心页面
		wx.getSetting({
			success(res) {
				//没有授权
				if (!res.authSetting['scope.userInfo']) {
					console.log('没有授权');
					wx.showModal({
						title: '提示',
						content: '您还没有授权本应用，请先点击登录完成授权',
						showCancel: false,
						success: function (res) {
							wx.reLaunch({
								url: '../my/index'
							})
						}
					})
				}
			}
		})
		//读取用户信息缓存，避免每次都要刷新
		that.catchUserInfo(cb);
	},
	catchUserInfo(cb) {
		let that = this;
		wx.getStorage({
			key: 'userInfo',
			success: function (res) {
				var userInfo = res;
				//容错机制
				setTimeout(function () {
					wx.getStorage({
						key: 'userInfo',
						success: function (res) {

							if (res.data.vipEndTime != userInfo.data.vipEndTime) {
								console.log("容错一次");
								that.login(cb);
							}
						}
					})
				}, 1500);
				//执行传进了的函数
				typeof cb == "function" && cb(userInfo)
			},
			fail: function () {
				setTimeout(function () {
					that.catchUserInfo(cb);
				}, 2000);

			}
		})
	},
	globalData: {
		url: 'https://wechat-program.maggie.vip/screenshot/',
		siteroot:'https://wechat-program.maggie.vip/',
		userInfo: null,
		openid: null,
		shop: null,
		token: ''
	},
	//參數分別是 地址，傳入參數，成功后執行函數
	connect: function (url, parameter, callback) {
		let that = this;
		wx.request({
			url: that.globalData.url + url, //仅为示例，并非真实的接口地址
			data: parameter,
			dataType: 'json',
			method: "POST",
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: function (res) {
				callback(res.data);
				//console.log(res.data);
			}
		})
	},
	//获取access_token
	getToken: function () {
		var that = this;
		that.connect("getToken.php", "", function (e) {
			that.globalData.token = e;
		});
	},
	format: function (shijianchuo) {

		//shijianchuo是整数，否则要parseInt转换
		var time = new Date(parseInt(shijianchuo * 1000));
		var y = time.getFullYear();
		var m = time.getMonth() + 1;
		var d = time.getDate();
		var h = time.getHours();
		var mm = time.getMinutes();
		var s = time.getSeconds();
		return y + '.' + this.padLeftZero(m) + '.' + this.padLeftZero(d) + ' ' + this.padLeftZero(h) + ':' + this.padLeftZero(mm) + ':' + this.padLeftZero(s);
	},
	padLeftZero:function(num,n){
		n = 2;
		return (Array(n).join(0) + num).slice(-n);
	},
	randomWord: function (randomFlag, min, max) {
		var str = "",
			range = min,
			arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

		// 随机产生
		if (randomFlag) {
			range = Math.round(Math.random() * (max - min)) + min;
		}
		for (var i = 0; i < range; i++) {
			var pos = Math.round(Math.random() * (arr.length - 1));
			str += arr[pos];
		}
		return str;
	},
	checkOptions:function(canvasData,type){
		var re = new RegExp('[\u4e00-\u9fa5]', 'g');
		//钱包地址校验
		if (re.test(canvasData.walletAddress)){
			wx.showToast({
				title: '钱包地址不能带有中文字符！',
				icon:'none'
			})
			return false;
		} 

		//token数量
		for(var i = 0; i < canvasData.tokenNum;i++) {
			//校验token数量
			if (!this.isNumber(canvasData['tokenNum' + i])) {
				wx.showToast({
					title: 'token数量需要是个数字！',
					icon: 'none'
				})
				return false;
			}
			//校验token行情
			if (!this.isNumber(canvasData['tokenPrice' + i])) {
				wx.showToast({
					title: 'token行情需要是个数字！',
					icon: 'none'
				})
				return false;
			}
			if(type == 2) {
				//校验冻结token
				if (!this.isNumber(canvasData['tokenDong' + i])) {
					wx.showToast({
						title: 'token冻结数量需要是个数字！',
						icon: 'none'
					})
					return false;
				}
			}
		}
		return true;
	},
	//imtoken交易记录提交校验
	checkOptions1: function (canvasData, type) {
		var re = new RegExp('[\u4e00-\u9fa5]', 'g');
		//钱包地址校验
		if (re.test(canvasData.fakuandizhi) || re.test(canvasData.shoukuandizhi)) {
			wx.showToast({
				title: '钱包地址不能带有中文字符！',
				icon: 'none'
			})
			return false;
		}
		if (!this.isNumber(canvasData.kuanggongfei)){
			wx.showToast({
				title: '矿工费需要是个数字！',
				icon: 'none'
			})
			return false;
		}
	
		return true;
	},
	isNumber: function (n){
		return !isNaN(parseFloat(n)) && isFinite(n);
	}
})